package com.me.study.producerAndConsumer;

import com.me.common.util.SleepUtil;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 单消费者、单生产者的 消费者模式
 *
 * @author ME
 * @date   2020/1/8
 */
public class WithBlockingQueue2 {

    private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(300);

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2);
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.submit(new Producer(barrier));
        service.submit(new Consumer(barrier));
    }

    static class Producer implements Runnable {
        private CyclicBarrier barrier;

        public Producer(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                barrier.await();
                while (new Random().nextInt(20) != 19) {
                    Random random = new Random();
                    int i = random.nextInt();
                    System.out.println("生产者" + Thread.currentThread().getName() + "  生产数据 " + i);
                    SleepUtil.ms(100);
                    queue.put(i);
                }

                // 约定 0 为终止标记，加入 0
                queue.put(0);
                System.out.println("加入终止标记");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {
        private CyclicBarrier barrier;

        public Consumer(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                barrier.await();
                while (true) {
                    Integer element = queue.take();

                    // 约定 0 为终止标记，检验读取到的值
                    if (element == 0) {
                        System.out.println("收到终止标记");
                        // 执行完主动退出进程
                        System.exit(0);
                    }

                    System.out.println("消费者" + Thread.currentThread().getName() + " 正在消费数据 " + element);
                    SleepUtil.ms(100);
                }
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

}
